package main

import (
	"Picture2Base64/readfilename"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
)

func Picture2Base64(fpath string) (BaseCode string) {
	f, err := os.Open(fpath)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer f.Close()
	b, err := ioutil.ReadAll(f)
	if err != nil {
		fmt.Println(err)
	}
	//获取图片类型
	pytpe := Ext(fpath)
	BaseHead := fmt.Sprintf("data:image/%s;base64", pytpe)
	str := fmt.Sprintf("%s,%s", BaseHead, base64.StdEncoding.EncodeToString(b))
	return str
}

//自定义获取后缀名
func Ext(path string) string {
	for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
		if path[i] == '.' {
			return path[i+1:]
		}
	}
	return ""
}

func main() {
	strl := readfilename.ReadFileDir("C:\\Users\\58294\\Pictures\\test", 20)
	for _, Fname := range strl {
		pstr := Picture2Base64("C:\\Users\\58294\\Pictures\\test\\" + Fname)
		fmt.Println(pstr)
	}
	//pstr := Picture2Base64("C:\\Users\\58294\\Pictures\\Saved Pictures\\timg (1).jpg")
	//fmt.Println(pstr)
}
